import React, { useState } from 'react';
import { Card, Tabs, Form, Input, Button, Select, Switch, message, Tooltip, Divider, Space, InputNumber } from 'antd';
import { useApiSettings } from '../../contexts/ApiSettingsContext';
import { CloudOutlined, KeyOutlined, DatabaseOutlined, InfoCircleOutlined } from '@ant-design/icons';

const { TabPane } = Tabs;
const { Option } = Select;

const ApiConnectorPanel: React.FC = () => {
  const { settings, updateSettings } = useApiSettings();
  const [loading, setLoading] = useState<Record<string, boolean>>({});

  const handleTest = async (serviceType: string) => {
    setLoading({ ...loading, [serviceType]: true });
    try {
      // Mock test connection for now
      const success = true; // Replace with actual test logic
      message.success(success ? '连接成功!' : '连接失败，请检查配置');
    } catch (error) {
      message.error('测试连接时出错');
    } finally {
      setLoading({ ...loading, [serviceType]: false });
    }
  };

  // Helper function to update nested settings
  const updateNestedSettings = (category: 'llm' | 'embedding' | 'retrieval', field: string, value: any) => {
    if (category === 'llm') {
      updateSettings({
        llm: {
          ...settings.llm,
          [field]: value
        }
      });
    } else if (category === 'embedding') {
      updateSettings({
        embedding: {
          ...settings.embedding,
          [field]: value
        }
      });
    } else if (category === 'retrieval') {
      updateSettings({
        retrieval: {
          ...settings.retrieval,
          [field]: value
        }
      });
    }
  };

  return (
    <Card title="API连接器" className="api-connector-panel">
      <Tabs defaultActiveKey="llm">
        <TabPane tab="LLM服务" key="llm">
          <Form layout="vertical" initialValues={settings.llm}>
            <Form.Item label="服务提供商">
              <Select 
                onChange={(value) => updateNestedSettings('llm', 'provider', value)}
                defaultValue={settings.llm.provider}
              >
                <Option value="openai">OpenAI</Option>
                <Option value="anthropic">Anthropic</Option>
                <Option value="azure">Azure OpenAI</Option>
                <Option value="custom">自定义</Option>
              </Select>
            </Form.Item>
            
            <Form.Item label="API端点">
              <Input 
                value={settings.llm.endpoint}
                onChange={(e) => updateNestedSettings('llm', 'endpoint', e.target.value)}
                placeholder="https://api.openai.com/v1/chat/completions" 
                addonBefore={<CloudOutlined />}
              />
            </Form.Item>
            
            <Form.Item 
              label="API密钥" 
              extra="您的API密钥将在本地安全存储，不会发送到我们的服务器"
            >
              <Input.Password 
                value={settings.llm.apiKey}
                onChange={(e) => updateNestedSettings('llm', 'apiKey', e.target.value)}
                addonBefore={<KeyOutlined />}
              />
            </Form.Item>
            
            <Form.Item label="模型名称">
              <Input 
                value={settings.llm.model}
                onChange={(e) => updateNestedSettings('llm', 'model', e.target.value)}
                placeholder="gpt-4" 
              />
            </Form.Item>
            
            <Button 
              type="primary" 
              onClick={() => handleTest('llm')}
              loading={loading['llm']}
            >
              测试连接
            </Button>
          </Form>
        </TabPane>
        
        <TabPane tab="Embedding服务" key="embedding">
          <Form layout="vertical" initialValues={settings.embedding}>
            <Form.Item label="服务提供商">
              <Select 
                onChange={(value) => updateNestedSettings('embedding', 'provider', value)}
                defaultValue={settings.embedding.provider}
              >
                <Option value="openai">OpenAI</Option>
                <Option value="azure">Azure OpenAI</Option>
                <Option value="cohere">Cohere</Option>
                <Option value="huggingface">HuggingFace</Option>
                <Option value="custom">自定义</Option>
              </Select>
            </Form.Item>
            
            <Form.Item label="API端点">
              <Input 
                value={settings.embedding.endpoint}
                onChange={(e) => updateNestedSettings('embedding', 'endpoint', e.target.value)}
                placeholder="https://api.openai.com/v1/embeddings" 
                addonBefore={<CloudOutlined />}
              />
            </Form.Item>
            
            <Form.Item label="API密钥">
              <Input.Password 
                value={settings.embedding.apiKey}
                onChange={(e) => updateNestedSettings('embedding', 'apiKey', e.target.value)}
                addonBefore={<KeyOutlined />}
              />
            </Form.Item>
            
            <Form.Item 
              label="模型名称"
              tooltip="不同的Embedding模型会产生不同维度的向量，请确保与知识库使用相同的模型"
            >
              <Input 
                value={settings.embedding.model}
                onChange={(e) => updateNestedSettings('embedding', 'model', e.target.value)}
                placeholder="text-embedding-ada-002" 
              />
            </Form.Item>
            
            <Form.Item label="高级设置">
              <Switch 
                checked={settings.embedding.showAdvanced}
                onChange={(checked) => updateNestedSettings('embedding', 'showAdvanced', checked)}
              /> 显示高级选项
            </Form.Item>
            
            {settings.embedding.showAdvanced && (
              <>
                <Form.Item label="向量维度">
                  <InputNumber 
                    value={settings.embedding.dimensions}
                    onChange={(value) => updateNestedSettings('embedding', 'dimensions', value)}
                    min={1}
                    max={4096}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
                
                <Form.Item label="归一化向量">
                  <Switch 
                    checked={settings.embedding.normalize}
                    onChange={(checked) => updateNestedSettings('embedding', 'normalize', checked)}
                  />
                  <Tooltip title="归一化向量可以提高余弦相似度搜索的准确性">
                    <InfoCircleOutlined style={{ marginLeft: 8 }} />
                  </Tooltip>
                </Form.Item>
                
                <Form.Item label="批处理大小">
                  <InputNumber 
                    value={settings.embedding.batchSize}
                    onChange={(value) => updateNestedSettings('embedding', 'batchSize', value)}
                    min={1}
                    max={100}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </>
            )}
            
            <Button 
              type="primary" 
              onClick={() => handleTest('embedding')}
              loading={loading['embedding']}
            >
              测试连接
            </Button>
          </Form>
        </TabPane>
        
        <TabPane tab="检索服务" key="retrieval">
          <Form layout="vertical" initialValues={settings.retrieval}>
            <Form.Item label="检索服务类型">
              <Select 
                onChange={(value) => updateNestedSettings('retrieval', 'type', value)}
                defaultValue={settings.retrieval.type}
              >
                <Option value="pinecone">Pinecone</Option>
                <Option value="weaviate">Weaviate</Option>
                <Option value="qdrant">Qdrant</Option>
                <Option value="elasticsearch">Elasticsearch</Option>
                <Option value="milvus">Milvus</Option>
                <Option value="custom">自定义</Option>
              </Select>
            </Form.Item>
            
            <Form.Item label="API端点">
              <Input 
                value={settings.retrieval.endpoint}
                onChange={(e) => updateNestedSettings('retrieval', 'endpoint', e.target.value)}
                placeholder="https://your-pinecone-index.pinecone.io" 
                addonBefore={<CloudOutlined />}
              />
            </Form.Item>
            
            <Form.Item label="API密钥">
              <Input.Password 
                value={settings.retrieval.apiKey}
                onChange={(e) => updateNestedSettings('retrieval', 'apiKey', e.target.value)}
                addonBefore={<KeyOutlined />}
              />
            </Form.Item>
            
            <Form.Item label="索引/集合名称">
              <Input 
                value={settings.retrieval.indexName}
                onChange={(e) => updateNestedSettings('retrieval', 'indexName', e.target.value)}
                placeholder="default" 
                addonBefore={<DatabaseOutlined />}
              />
            </Form.Item>
            
            <Form.Item label="命名空间/分区">
              <Input 
                value={settings.retrieval.namespace}
                onChange={(e) => updateNestedSettings('retrieval', 'namespace', e.target.value)}
                placeholder="(可选) 命名空间或分区" 
              />
            </Form.Item>
            
            <Form.Item label="向量维度">
              <InputNumber 
                value={settings.retrieval.dimensions}
                onChange={(value) => updateNestedSettings('retrieval', 'dimensions', value)}
                min={1}
                max={4096}
                style={{ width: '100%' }}
              />
              <div style={{ marginTop: 8, color: '#999' }}>
                <InfoCircleOutlined /> 确保与Embedding模型维度一致
              </div>
            </Form.Item>
            
            <Form.Item label="检索服务状态">
              <Space>
                <Button 
                  type="primary" 
                  onClick={() => handleTest('retrieval')}
                  loading={loading['retrieval']}
                >
                  测试连接
                </Button>
                
                <Button 
                  onClick={() => {
                    setLoading({ ...loading, 'retrievalInfo': true });
                    // 查询索引信息并显示
                    setTimeout(() => {
                      message.success('查询成功：索引包含1,254条记录，最后更新于2023-11-10');
                      setLoading({ ...loading, 'retrievalInfo': false });
                    }, 1000);
                  }}
                  loading={loading['retrievalInfo']}
                >
                  查询索引信息
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </TabPane>
      </Tabs>
    </Card>
  );
};

export default ApiConnectorPanel; 